package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.client.ArticleFeign;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.entity.ApUserInfo;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.ApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.ApUserService;
import com.heima.wemedia.client.WemediaFeign;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author RMY
 * @since 2021-11-24
 */
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {
    @Autowired
    private ApUserService apUserService;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    /**
     * 分页查询用户认证信息
     * @param authDto
     * @return
     */
    @Override
    public PageResult<UserAuthDto> loadListByStatus(AuthDto authDto) {
        //1.接受参数,判断
        QueryWrapper<ApUserAuth> qw = new QueryWrapper<>();
        if (authDto.getStatus() != null && authDto !=null){
            qw.lambda().eq(ApUserAuth::getStatus,authDto.getStatus());
        }
        //2.开启分页
        IPage pageParam = new Page(authDto.getPage(),authDto.getSize());
        IPage iPage = page(pageParam, qw);
        //3.判断查询结果
        if (iPage == null || CollectionUtils.isEmpty(iPage.getRecords())){
            //不存在抛出异常
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4.封装结果
        List<UserAuthDto> userAuthDtoList = BeanHelper.copyWithCollection(iPage.getRecords(), UserAuthDto.class);
        return new PageResult<>(authDto.getPage(),authDto.getSize(),iPage.getTotal(),userAuthDtoList);

    }


    /**
     * 审核通过
     * @param authDto
     * @return
     */
    @Override
    @GlobalTransactional
    public void authPassOrauthFail(AuthDto authDto, int status) {
        //1.获取参数
        //2.更新表
        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(authDto.getId());
        apUserAuth.setStatus(status);
        apUserAuth.setUpdatedTime(new Date());
        if (status == 2){
            //拒绝通过理由
            apUserAuth.setReason(authDto.getMsg());
        }
        //2,2根据主键更新
        boolean b = updateById(apUserAuth);
        if (!b){
            //抛出异常
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        if (status == 2){
            //直接返回
            return ;
        }
        //更新ApUser状态
        //根据AuthDto的主键找到ApUserAuth
        //3.在自媒体wemedia数据库we_user表中插入一条新数据
        apUserAuth = getById(authDto.getId());
        Integer apUserId = apUserAuth.getUserId();
        ApUser apUser = apUserService.getById(apUserId);
        //封装自媒体人表
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setApUserId(apUserId);
        wmUserDto.setName(apUser.getName());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setImage(apUser.getImage());
        wmUserDto.setPhone(apUser.getPhone());
        //远程调用feign
        try {
            Integer wmUserId = wemediaFeign.save(wmUserDto);
            wmUserDto.setId(wmUserId);
        } catch (Exception e) {
            log.error("远程调用wemedia失败");
            e.printStackTrace();
        }
        //4.在article数据库中的author表中插入一条数据
        AuthorDto authorDto = new AuthorDto();
        authorDto.setWmUserId(wmUserDto.getId());
        authorDto.setName(apUser.getName());
        authorDto.setType(2);
        authorDto.setUserId(apUserId);
        //feign调用
        try {
            Integer authorId = articleFeign.save(authorDto);
        } catch (Exception e) {
            log.error("远程调用article失败");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,e.getMessage());
        }
        //4.修改apUser字段
        apUser = new ApUser();
        apUser.setId(apUserId);
        apUser.setFlag(1);
        boolean b1 = apUserService.updateById(apUser);
        if (!b1){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //int i = 1/0;
    }
}
